package com.v3admin.system.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.v3admin.common.enums.UserCreateTypeEnum;
import com.v3admin.common.enums.UserStatusEnum;
import com.v3admin.common.exception.BusinessException;
import com.v3admin.common.service.IServiceImpl;
import com.v3admin.system.config.UserPasswordRsaConfig;
import com.v3admin.system.domain.SystemUser;
import com.v3admin.system.mapper.SystemUserMapper;
import com.v3admin.system.service.SystemUserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 系统用户
 *
 * @author Junpeng.Li
 * @date 2023-12-11 17:16
 */
@Service
@AllArgsConstructor
public class SystemUserServiceImpl extends IServiceImpl<SystemUserMapper, SystemUser> implements SystemUserService {

    private final UserPasswordRsaConfig rsaConfig;

    @Override
    public SystemUser getByUsername(String username) {
        QueryWrapper<SystemUser> wrapper = queryWrapper(item -> item.eq(SystemUser.TBF_USERNAME, username));
        return super.getOne(wrapper, false);
    }

    @Override
    public SystemUser getByEmail(String email) {
        QueryWrapper<SystemUser> wrapper = queryWrapper(item -> item.eq(SystemUser.TBF_EMAIL, email));
        return super.getOne(wrapper, false);
    }

    @Override
    public boolean save(SystemUser entity) {
        if (null != this.getByUsername(entity.getUsername())) {
            throw new BusinessException("用户名[ {} ]已存在", entity.getUsername());
        }
        if (null != this.getByEmail(entity.getEmail())) {
            throw new BusinessException("邮箱地址[ {} ]已被注册", entity.getEmail());
        }

        // 解密密码
        String password = SaSecureUtil.rsaDecryptByPrivate(rsaConfig.getPrivateKey(), entity.getPassword());
        // 加密密码，防止密码泄露
        entity.setPassword(encryptPassword(password));
        entity.setStatus(UserStatusEnum.normal);
        entity.setCreateType(UserCreateTypeEnum.admin_add);
        return super.save(entity);
    }

    @Override
    public String encryptPassword(String password) {
        return SaSecureUtil.md5(password);
    }

    @Override
    public void freeze(Long userId, Date endTime) {
        SystemUser entity = new SystemUser();
        entity.setId(userId);
        entity.setStatus(UserStatusEnum.freeze);
        entity.setFreezeStartTime(new Date());
        entity.setFreezeEndTime(endTime);
        super.updateById(entity);
    }

}
